package Fly.example.controller;


import Fly.example.common.R;
import Fly.example.dto.DishDto;
import Fly.example.pojo.Category;
import Fly.example.pojo.Dish;
import Fly.example.pojo.DishFlavor;
import Fly.example.service.ICategoryService;
import Fly.example.service.IDishFlavorService;
import Fly.example.service.IDishService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 前端控制器
 * </p>
 *
 * @author 陽Fly
 * @since 2025-06-14
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private IDishService dishService;

    @Autowired
    private IDishFlavorService dishFlavorService;

    @Autowired
    private ICategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 查询列表接口
    //菜品信息分页
    //还需要菜品对应的分类
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        log.info("查询菜品业务开始…………");
        //初始化分页器
        Page<Dish> pageinfo = new Page(page, pageSize);
        //创建一个dto的分页构造器
        Page<DishDto> pagedto = new Page();
        //分页条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.like(name != null,Dish::getName, name);
        //添加排序条件
        queryWrapper.orderByDesc(Dish::getPrice);
        dishService.page(pageinfo, queryWrapper);
        //将dish拷贝到dto里去
        BeanUtils.copyProperties(pageinfo, pagedto,"redords");
        List<Dish> records = pageinfo.getRecords();
        //通过stream流的方式给dto里面的categoryId赋值
        List<DishDto> list = records.stream().map(item -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item,dto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //查询到的不是空才能进行赋值操作，否则不进行赋值操作，直接返回空
            if (category != null) {
                String categoryName = category.getName();
                dto.setCategoryName(categoryName);
            }else{
                dto.setCategoryName("暂无分类");
            }
            return dto;
        }).collect(Collectors.toList());//最终返回一个dto的集合
        //设置dto里的集合
        pagedto.setRecords(list);
        //返回dto数据
        return R.success(pagedto);
    }

    // 删除接口
    //删除的不需要清理缓存，因为只能删除停售的
    @DeleteMapping
    public R<String> del(String[] ids) {
        log.info("删除菜品业务开始");
        dishService.removeByIds(Arrays.asList(ids));
        return R.success("删除成功");
    }

    // 新增接口
    @PostMapping
    public R<String> add(@RequestBody DishDto dishdto) {
        log.info("新增业务开始");
        dishService.SaveWithflavor(dishdto);
        //清理某个分类的菜品的缓存
        String key = "dish_" + dishdto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    //修改菜品(页面回显的数据,菜品信息以及对应的口味信息)
    @GetMapping("/{id}")
    public R<DishDto> set(@PathVariable long id){
        log.info("要修改的菜品的id为{}",id);
/*        Dish dish = dishService.getById(id);
        Long dishId = dish.getId();
        DishDto dto = new DishDto();
        BeanUtils.copyProperties(dish,dto);
        dishFlavorService.lambdaQuery().eq(DishFlavor::getDishId,dishId);*/
        DishDto dishWithFlavor = dishService.getDishWithFlavor(id);
        return R.success(dishWithFlavor);
    }

    //修改菜品
    //修改菜品信息，同时修改口味
    @PutMapping
    public R<String> updata(@RequestBody DishDto dishdto) {
        log.info("修改菜品业务开始…………");
        //log.info("要修改的菜品信息欸：{}，同时修改口味为：{}",dishdto,dishdto.getFlavors());
        dishService.updataWithflavor(dishdto);

        //清理某个分类的菜品的缓存
        String key = "dish_" + dishdto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    //停售业务
    //起售停售---批量起售停售接口
    @PostMapping("/status/{status}")
    public R<String> setStatus(String ids, @PathVariable int status) {
        log.info("停售/批量停售业务开始…………");
        log.info("id为：{}，修改状态为：{}",ids,status);
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        String[] split = ids.split(",");
        //如果传进来的参数为多个，就使用分割，得到每一个id，然后再进行条件更新
        for (int i = 0; i < split.length; i++) {
            queryWrapper.eq(Dish::getId, split[i]);
        }
        Dish dish = new Dish()
                .setStatus(status);
        dishService.update(dish,queryWrapper);
        return R.success("修改菜品状态成功");
    }

    //用于移动端的数据回显，根据category_id查询
    @GetMapping("/list")
    public R<List<DishDto>> see(Dish dish) {
        log.info("category_id为{}",dish.getCategoryId());

        List<DishDto> dishDto = null;
        //动态构造,主要的是这个的设计
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();

        //先查询redis里面有没有缓存
        dishDto = (List<DishDto>) redisTemplate.opsForValue().get(key);

        if(dishDto != null){
            return R.success(dishDto);
        }



        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId())
                .eq(Dish::getStatus,1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        dishDto = list.stream().map(item -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item,dto);
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //查询到的不是空才能进行赋值操作，否则不进行赋值操作，直接返回空
            if (category != null) {
                String categoryName = category.getName();
                dto.setCategoryName(categoryName);
            }else{
                dto.setCategoryName("暂无分类");
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> queryWrapper1 = new LambdaQueryWrapper<>();
            //根据dishid查询出口味信息表
            queryWrapper1.eq(DishFlavor::getDishId,dishId);
            List<DishFlavor> list1 = dishFlavorService.list(queryWrapper1);
            //在dto里面设置口味传给前端
            dto.setFlavors(list1);
            return dto;
        }).collect(Collectors.toList());

        //如果没有再查数据库，并且要加入到缓存
        redisTemplate.opsForValue().set(key, dishDto,60, TimeUnit.MINUTES);

        return R.success(dishDto);
    }



}
